from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                               QPushButton, QFrame, QScrollArea, QWidget, QGridLayout)
from PySide6.QtCore import Qt, Signal, QSize, QPropertyAnimation, QEasingCurve, QRect
from PySide6.QtGui import QFont, QColor, QPalette, QIcon, QPixmap, QPainter, QLinearGradient


class ColorBar(QWidget):
    """颜色条预览组件"""

    def __init__(self, colors, parent=None):
        super().__init__(parent)
        self.colors = colors
        self.setFixedHeight(8)
        self.setMinimumWidth(160)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        rect = self.rect()
        color_width = rect.width() / len(self.colors)

        for i, color in enumerate(self.colors):
            color_rect = QRect(int(i * color_width), 0, int(color_width), rect.height())
            painter.fillRect(color_rect, QColor(color))

        # 添加圆角效果
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(QColor(0, 0, 0, 0))
        painter.drawRoundedRect(rect, 4, 4)


class ThemePreviewCard(QFrame):
    """主题预览卡片"""
    clicked = Signal(str)

    def __init__(self, theme_key, theme_data, is_selected=False, parent=None):
        super().__init__(parent)
        self.theme_key = theme_key
        self.theme_data = theme_data
        self.is_selected = is_selected
        self.animation = None
        self.setup_ui()

    def setup_ui(self):
        self.setFixedSize(220, 200)
        self.setCursor(Qt.CursorShape.PointingHandCursor)

        # 设置基础样式
        self.update_style()

        layout = QVBoxLayout(self)
        layout.setContentsMargins(16, 16, 16, 16)
        layout.setSpacing(12)

        # 主题名称
        name_label = QLabel(self.theme_data['name'])
        name_label.setFont(QFont("Microsoft YaHei", 14, QFont.Weight.Bold))
        name_label.setStyleSheet(f"color: {self.theme_data['text']}; background: transparent;")
        name_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(name_label)

        # 主题描述
        desc_label = QLabel(self.theme_data['description'])
        desc_label.setFont(QFont("Microsoft YaHei", 9))
        desc_label.setStyleSheet(f"color: {self.theme_data['text_secondary']}; background: transparent;")
        desc_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        desc_label.setWordWrap(True)
        layout.addWidget(desc_label)

        # 颜色预览区域
        colors_container = QWidget()
        colors_layout = QVBoxLayout(colors_container)
        colors_layout.setContentsMargins(0, 8, 0, 8)
        colors_layout.setSpacing(8)

        # 主要颜色圆点
        main_colors_widget = QWidget()
        main_colors_layout = QHBoxLayout(main_colors_widget)
        main_colors_layout.setContentsMargins(0, 0, 0, 0)
        main_colors_layout.setSpacing(8)
        main_colors_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # 添加主要颜色样本
        main_colors = [
            self.theme_data['primary'],
            self.theme_data['secondary'],
            self.theme_data['accent']
        ]

        for color in main_colors:
            color_sample = QFrame()
            color_sample.setFixedSize(24, 24)
            color_sample.setStyleSheet(f"""
                background-color: {color};
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.8);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            """)
            main_colors_layout.addWidget(color_sample)

        colors_layout.addWidget(main_colors_widget)

        # 颜色条预览
        color_bar_colors = [
            self.theme_data['primary'],
            self.theme_data['accent'],
            self.theme_data['secondary'],
            self.theme_data['success'],
            self.theme_data['warning']
        ]

        color_bar = ColorBar(color_bar_colors)
        color_bar.setStyleSheet("""
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        """)
        colors_layout.addWidget(color_bar)

        layout.addWidget(colors_container)

        # 选中状态指示器
        self.status_label = QLabel()
        self.status_label.setFont(QFont("Microsoft YaHei", 10, QFont.Weight.Bold))
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.update_status_label()
        layout.addWidget(self.status_label)

        layout.addStretch()

    def update_style(self):
        """更新卡片样式"""
        if self.is_selected:
            border_color = self.theme_data['primary']
            border_width = "3px"
            shadow_color = self.theme_data['primary'].replace('#', '').lower()
            # 将hex转换为rgba
            r = int(shadow_color[0:2], 16)
            g = int(shadow_color[2:4], 16)
            b = int(shadow_color[4:6], 16)
            box_shadow = f"0 8px 25px rgba({r}, {g}, {b}, 0.3)"
        else:
            border_color = self.theme_data['border']
            border_width = "2px"
            box_shadow = "0 4px 15px rgba(0, 0, 0, 0.1)"

        self.setStyleSheet(f"""
            ThemePreviewCard {{
                background: {self.theme_data['card_bg']};
                border: {border_width} solid {border_color};
                border-radius: 16px;
                box-shadow: {box_shadow};
            }}
            ThemePreviewCard:hover {{
                border: 3px solid {self.theme_data['accent']};
                box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
                transform: translateY(-2px);
            }}
        """)

    def update_status_label(self):
        """更新状态标签"""
        if self.is_selected:
            self.status_label.setText("✓ 当前使用")
            self.status_label.setStyleSheet(f"""
                color: {self.theme_data['primary']};
                background: rgba(255, 255, 255, 0.8);
                border-radius: 12px;
                padding: 4px 12px;
            """)
        else:
            self.status_label.setText("点击应用")
            self.status_label.setStyleSheet(f"""
                color: {self.theme_data['text_secondary']};
                background: transparent;
            """)

    def set_selected(self, selected):
        """设置选中状态"""
        if self.is_selected != selected:
            self.is_selected = selected
            self.update_style()
            self.update_status_label()

            # 添加选中动画效果
            if selected:
                self.animate_selection()

    def animate_selection(self):
        """选中动画效果"""
        if self.animation:
            self.animation.stop()

        self.animation = QPropertyAnimation(self, b"geometry")
        self.animation.setDuration(200)
        self.animation.setEasingCurve(QEasingCurve.Type.OutCubic)

        current_rect = self.geometry()
        # 轻微的缩放效果
        target_rect = QRect(
            current_rect.x() - 2,
            current_rect.y() - 2,
            current_rect.width() + 4,
            current_rect.height() + 4
        )

        self.animation.setStartValue(current_rect)
        self.animation.setEndValue(target_rect)
        self.animation.finished.connect(lambda: self.setGeometry(current_rect))
        self.animation.start()

    def mousePressEvent(self, event):
        """鼠标点击事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.clicked.emit(self.theme_key)
        super().mousePressEvent(event)


class ThemeDialog(QDialog):
    """主题选择对话框"""
    theme_changed = Signal(str)

    def __init__(self, theme_manager, parent=None):
        super().__init__(parent)
        self.theme_manager = theme_manager
        self.current_theme = theme_manager.get_current_theme()
        self.selected_theme = self.current_theme
        self.theme_cards = {}

        self.setup_ui()
        self.apply_current_theme()

    def setup_ui(self):
        """设置用户界面"""
        self.setWindowTitle("🎨 主题设置")
        self.setFixedSize(800, 600)
        self.setModal(True)

        # 设置窗口标志，移除问号按钮
        self.setWindowFlags(
            Qt.WindowType.Dialog |
            Qt.WindowType.WindowTitleHint |
            Qt.WindowType.WindowCloseButtonHint
        )

        layout = QVBoxLayout(self)
        layout.setContentsMargins(24, 24, 24, 24)
        layout.setSpacing(20)

        # 标题区域
        title_container = QWidget()
        title_layout = QVBoxLayout(title_container)
        title_layout.setContentsMargins(0, 0, 0, 0)
        title_layout.setSpacing(8)

        title_label = QLabel("选择您喜欢的主题")
        title_label.setFont(QFont("Microsoft YaHei", 20, QFont.Weight.Bold))
        title_layout.addWidget(title_label)

        subtitle_label = QLabel("每个主题都经过精心设计，为您提供最佳的视觉体验")
        subtitle_label.setFont(QFont("Microsoft YaHei", 11))
        title_layout.addWidget(subtitle_label)

        layout.addWidget(title_container)

        # 主题预览区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.Shape.NoFrame)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)

        themes_container = QWidget()
        themes_layout = QGridLayout(themes_container)
        themes_layout.setContentsMargins(10, 10, 10, 10)
        themes_layout.setSpacing(20)

        # 添加所有主题预览卡片
        all_themes = self.theme_manager.get_all_themes()
        row, col = 0, 0

        for theme_key, theme_data in all_themes.items():
            theme_card = ThemePreviewCard(
                theme_key,
                theme_data,
                is_selected=(theme_key == self.current_theme)
            )
            theme_card.clicked.connect(self.on_theme_selected)
            self.theme_cards[theme_key] = theme_card

            themes_layout.addWidget(theme_card, row, col)

            col += 1
            if col >= 3:  # 每行3个
                col = 0
                row += 1

        # 添加弹性空间
        themes_layout.setRowStretch(row + 1, 1)
        themes_layout.setColumnStretch(3, 1)

        scroll_area.setWidget(themes_container)
        layout.addWidget(scroll_area)

        # 底部按钮区域
        buttons_container = QFrame()
        buttons_container.setFixedHeight(60)
        buttons_layout = QHBoxLayout(buttons_container)
        buttons_layout.setContentsMargins(0, 0, 0, 20)
        buttons_layout.setSpacing(12)

        # 预览按钮
        self.preview_button = QPushButton("👁️ 预览效果")
        self.preview_button.setEnabled(False)
        self.preview_button.clicked.connect(self.preview_theme)

        # 应用按钮
        self.apply_button = QPushButton("✨ 应用主题")
        self.apply_button.setEnabled(False)
        self.apply_button.clicked.connect(self.apply_theme)

        # 取消按钮
        cancel_button = QPushButton("❌ 取消")
        cancel_button.clicked.connect(self.reject)

        buttons_layout.addStretch()
        buttons_layout.addWidget(self.preview_button)
        buttons_layout.addWidget(self.apply_button)
        buttons_layout.addWidget(cancel_button)

        layout.addWidget(buttons_container)

    def apply_current_theme(self):
        """应用当前主题到对话框"""
        theme_data = self.theme_manager.get_theme_data()

        self.setStyleSheet(f"""
            ThemeDialog {{
                background: {theme_data['background']};
                color: {theme_data['text']};
            }}
            QLabel {{
                color: {theme_data['text']};
                background: transparent;
            }}
            QPushButton {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme_data['gradient_start']}, 
                    stop:1 {theme_data['gradient_end']});
                color: white;
                border-radius: 8px;
                padding: 10px 20px;
                font-weight: bold;
                border: none;
                min-width: 100px;
            }}
            QPushButton:hover {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme_data['accent']}, 
                    stop:1 {theme_data['primary']});
            }}
            QPushButton:pressed {{
                background: {theme_data['secondary']};
            }}
            QPushButton:disabled {{
                background: {theme_data['text_secondary']};
                color: rgba(255, 255, 255, 0.6);
            }}
            QScrollArea {{
                background: transparent;
                border: none;
            }}
            QScrollBar:vertical {{
                background: {theme_data['background']};
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }}
            QScrollBar::handle:vertical {{
                background: {theme_data['primary']};
                border-radius: 6px;
                min-height: 20px;
            }}
            QScrollBar::handle:vertical:hover {{
                background: {theme_data['accent']};
            }}
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
                height: 0px;
            }}
        """)

    def on_theme_selected(self, theme_key):
        """主题选择事件处理"""
        if theme_key != self.selected_theme:
            # 更新之前选中的卡片
            if self.selected_theme in self.theme_cards:
                self.theme_cards[self.selected_theme].set_selected(False)

            # 更新新选中的卡片
            self.selected_theme = theme_key
            if theme_key in self.theme_cards:
                self.theme_cards[theme_key].set_selected(True)

            # 启用按钮
            is_different = (theme_key != self.current_theme)
            self.preview_button.setEnabled(is_different)
            self.apply_button.setEnabled(is_different)

    def preview_theme(self):
        """预览主题效果"""
        if self.selected_theme != self.current_theme:
            # 临时应用主题到对话框
            old_theme = self.theme_manager.current_theme
            self.theme_manager.current_theme = self.selected_theme
            self.apply_current_theme()

            # 显示预览提示
            theme_data = self.theme_manager.get_theme_data(self.selected_theme)
            self.setWindowTitle(f"🎨 主题预览 - {theme_data['name']}")

            # 恢复原主题设置（不保存到数据库）
            self.theme_manager.current_theme = old_theme

    def apply_theme(self):
        """应用选中的主题"""
        if self.selected_theme and self.selected_theme != self.current_theme:
            success = self.theme_manager.set_theme(self.selected_theme)
            if success:
                self.current_theme = self.selected_theme
                self.theme_changed.emit(self.selected_theme)

                # 更新按钮状态
                self.apply_button.setEnabled(False)
                self.preview_button.setEnabled(False)

                # 更新窗口标题
                theme_data = self.theme_manager.get_theme_data()
                self.setWindowTitle(f"🎨 主题设置 - 已应用 {theme_data['name']}")

                # 重新应用主题到对话框
                self.apply_current_theme()

                # 延迟关闭对话框
                # from PySide6.QtCore import QTimer
                # QTimer.singleShot(1000, self.accept)

    def reject(self):
        """取消对话框"""
        # 确保恢复到原始主题
        if hasattr(self, 'original_theme'):
            self.theme_manager.current_theme = self.original_theme
        super().reject()

    def showEvent(self, event):
        """显示事件"""
        # 保存原始主题
        self.original_theme = self.theme_manager.current_theme
        super().showEvent(event)

